<?php
namespace Application\Api\Controller;

class ImageValidCode extends Base
{

    /*
        /Api/ImageValidCode/make?w=100&h=38
    */
    public function makeAction()
    {
        $data = $this->getRequestData();
        $coreImageValidCode = $this->get(CORE_IMAGEVALIDCODE);
        $cacheCommon = $this->get(CACHE_COMMON);
        $code = $coreImageValidCode->setWidthHeight($data['w'], $data['h'])->getCode();
        $name = uniqid();
        $cacheCommon->setData($name, HALF_HOUR_SECOND, $code);
        $content = $coreImageValidCode->makeImage();
        $data = [
            'name' => $name,
            'content' => 'data:image/png;base64,' . base64_encode($content)
        ];
        $this->sendSuccess($data);
    }

    public function checkAction()
    {
        $data = $this->getRequestData();
        if(notSetOrEmpty($data, 'imageName')){
            $this->sendFail('PARAMETER_ERROR', 'imageName参数错误');
            return false;
        }
        if(notSetOrEmpty($data, 'imageCode')){
            $this->sendFail('PARAMETER_ERROR', 'imageCode参数错误');
            return false;
        }
        /*验证码是否正确*/
        $cacheCommon = $this->get(CACHE_COMMON);
        $code = $cacheCommon->getData($data['imageName']);
        if(!checkValidCode($code, $data['imageCode'])){
            $this->sendFail('VALID_CODE_ERROR');
            return false;
        }
        else{
            $this->sendSuccess();
        }
    }

}